package com.teamwhole.modules.sys.web;

import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.teamwhole.common.utils.StringUtils;
import com.teamwhole.modules.sys.security.FormAuthenticationFilter;

@Component
@Path("/login")
public class LoginResource {

	@Context
	private HttpServletRequest request;
	
	@Context
	private HttpServletResponse response;
	
	 /**
     * 登录页面
     * @return
     */
	@GET
	public Response login() throws Exception {
		String loginURL = new StringBuilder(request.getContextPath()).append("/page/login").toString();
		URI uri = new URI(loginURL);
		return Response.seeOther(uri).build();
	}

	/**
     * 真正登录的POST请求由Filter完成
     * (登录失败时调用)
     */
	@POST
	public void loginFailure() throws Exception {
		String error = "账号或密码错误.";
		String shiroLoginFailure = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if (StringUtils.isNoneBlank(shiroLoginFailure)) {
			if ("randomCodeError".equals(shiroLoginFailure)) {
				error = "验证码输入错误.";
			}
		}
		if (StringUtils.isBlank(shiroLoginFailure)) {
			response.sendRedirect(request.getContextPath() + "/page/index");
		}
		request.setAttribute("error", error);
		request.getRequestDispatcher("/WEB-INF/views/modules/login.jsp").forward(request, response);
	}

}
